package com.qin.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qin.entity.User;
import com.qin.service.UserService;
import com.qin.service.impl.UserServiceImpl;

import cn.hutool.log.StaticLog;

/**
 * 动态监测注册时发过来的用户名和数据库中的人名是否冲突
 */
@WebServlet("/checkname")
public class DynamicCheckNameOrEmailServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    private UserService userService = new UserServiceImpl();
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		StaticLog.debug("开始对用户名或者是邮箱是否重复进行判断");
		// 拿到用户名和邮箱
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		
		if(name != null) {
			PrintWriter writer = response.getWriter();
			// 去数据库查
			User userByName = userService.queryUserByNameOrByEmail(name, false);
			
			StaticLog.debug("查询完毕，通过名字：{}", userByName);
			
			// 查到了，就代表有重名
			if(userByName != null) {
				writer.print(true);
				
			}
			
			writer.flush();
			writer.close();
		}
		
		if(email != null) {
			PrintWriter writer = response.getWriter();
			// 查邮箱
			User userByEmail = userService.queryUserByNameOrByEmail(email, true);
			
			StaticLog.debug("查询完毕，通过邮箱：{}", userByEmail);
			if(userByEmail != null) {
				writer.print(true);
			}
			writer.flush();
			writer.close();
		}
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
